<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/agul.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/agul.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/agul.png?v=5.1.4">






  <meta name="keywords" content="服务端笔记,Node," />




  


  <link rel="alternate" href="/atom.xml" title="Agul'blog" type="application/atom+xml" />






<meta name="description" content="Node.js 创建Web服务器创建文件app.js 123456789101112 &#x2F;&#x2F; 引用系统模块httpconst http &#x3D; require(&#39;http&#39;); &#x2F;&#x2F; 创建web服务器const app &#x3D; http.createServer(); &#x2F;&#x2F; 当客户端发送请求的时候app.on(&#39;request&#39;, (req, res) &#x3D;&gt; &amp;#123;       &#x2F;&#x2F;  响应">
<meta property="og:type" content="article">
<meta property="og:title" content="http协议和Node.js异步编程">
<meta property="og:url" content="https://ultraman-agul.github.io/2020/05/21/http%E5%8D%8F%E8%AE%AE%E5%92%8CNode.js%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/index.html">
<meta property="og:site_name" content="Agul&#39;blog">
<meta property="og:description" content="Node.js 创建Web服务器创建文件app.js 123456789101112 &#x2F;&#x2F; 引用系统模块httpconst http &#x3D; require(&#39;http&#39;); &#x2F;&#x2F; 创建web服务器const app &#x3D; http.createServer(); &#x2F;&#x2F; 当客户端发送请求的时候app.on(&#39;request&#39;, (req, res) &#x3D;&gt; &amp;#123;       &#x2F;&#x2F;  响应">
<meta property="og:image" content="https://ultraman-agul.github.io/images/%E8%B7%AF%E7%94%B1.PNG">
<meta property="article:published_time" content="2020-05-21T04:47:37.693Z">
<meta property="article:modified_time" content="2020-05-21T07:39:22.593Z">
<meta property="article:author" content="agul">
<meta property="article:tag" content="服务端笔记">
<meta property="article:tag" content="Node">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ultraman-agul.github.io/images/%E8%B7%AF%E7%94%B1.PNG">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://ultraman-agul.github.io/2020/05/21/http协议和Node.js异步编程/"/>





  <title>http协议和Node.js异步编程 | Agul'blog</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Agul'blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Record a good life</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://ultraman-agul.github.io/2020/05/21/http%E5%8D%8F%E8%AE%AE%E5%92%8CNode.js%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="agul">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/agul1.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Agul'blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">http协议和Node.js异步编程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-05-21T12:47:37+08:00">
                2020-05-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%9C%8D%E5%8A%A1%E7%AB%AF/" itemprop="url" rel="index">
                    <span itemprop="name">服务端</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Node-js-创建Web服务器"><a href="#Node-js-创建Web服务器" class="headerlink" title="Node.js 创建Web服务器"></a>Node.js 创建Web服务器</h1><p>创建文件app.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// 引用系统模块http</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"> <span class="comment">// 创建web服务器</span></span><br><span class="line"><span class="keyword">const</span> app = http.createServer();</span><br><span class="line"> <span class="comment">// 当客户端发送请求的时候</span></span><br><span class="line">app.on(<span class="string">'request'</span>, (req, res) =&gt; &#123;</span><br><span class="line">       <span class="comment">//  响应</span></span><br><span class="line">      res.end(<span class="string">'&lt;h1&gt;hi, user&lt;/h1&gt;'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"> <span class="comment">// 监听3000端口</span></span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'服务器已启动'</span>)</span><br></pre></td></tr></table></figure>

<p>此时只需要在浏览器访问<code>localhost:3000</code>即可访问服务器</p>
<h1 id="http"><a href="#http" class="headerlink" title="http"></a>http</h1><h3 id="请求报文："><a href="#请求报文：" class="headerlink" title="请求报文："></a>请求报文：</h3><ul>
<li>GET 请求数据</li>
<li>POST 发送数据</li>
</ul>
<p>获取请求信息：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">app.on(<span class="string">'request'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    req.headers  <span class="comment">// 获取请求报文</span></span><br><span class="line">    req.url      <span class="comment">// 获取请求地址</span></span><br><span class="line">    req.method   <span class="comment">// 获取请求方法</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="响应报文"><a href="#响应报文" class="headerlink" title="响应报文"></a>响应报文</h3><p>http状态码：</p>
<ul>
<li>200 请求成功</li>
<li>404 Not Found</li>
<li>500 服务器端错误</li>
<li>400 客户端请求语法错误</li>
</ul>
<p>内容类型：</p>
<ul>
<li>text/html</li>
<li>text/css</li>
<li>application/javascript</li>
<li>image/jpeg</li>
<li>application/json</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 设置响应报文</span></span><br><span class="line">     res.writeHead(<span class="number">200</span>, &#123;<span class="string">'Content-Type'</span>: <span class="string">'text/html;charset=utf8'</span>&#125;);</span><br></pre></td></tr></table></figure>



<h3 id="GET请求参数"><a href="#GET请求参数" class="headerlink" title="GET请求参数"></a>GET请求参数</h3><ul>
<li>参数被放置在浏览器<strong>地址栏</strong>中，是不安全的，例如：<a href="http://localhost:3000/?name=zhangsan&amp;age=20" target="_blank" rel="noopener">http://localhost:3000/?name=zhangsan&amp;age=20</a></li>
<li>参数获取需要借助系统模块url，url模块用来处理url地址</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="comment">// 导入url系统模块 用于处理url地址</span></span><br><span class="line"><span class="keyword">const</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>);</span><br><span class="line"><span class="keyword">const</span> app = http.createServer();</span><br><span class="line">app.on(<span class="string">'request'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    <span class="comment">// 将url路径的各个部分解析出来并返回对象</span></span><br><span class="line">        <span class="comment">// true 代表将参数解析为对象格式</span></span><br><span class="line">    <span class="keyword">let</span> &#123;query&#125; = url.parse(req.url, <span class="literal">true</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(query);</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>



<h3 id="POST请求参数"><a href="#POST请求参数" class="headerlink" title="POST请求参数"></a>POST请求参数</h3><ul>
<li><p>参数被放置在<strong>请求体</strong>中进行传输</p>
</li>
<li><p>获取POST参数需要使用<code>data</code>事件和<code>end</code>事件</p>
</li>
<li><p>使用<code>querystring</code>系统模块将参数转换为对象格式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入系统模块querystring 用于将HTTP参数转换为对象格式</span></span><br><span class="line"><span class="keyword">const</span> querystring = <span class="built_in">require</span>(<span class="string">'querystring'</span>);</span><br><span class="line">app.on(<span class="string">'request'</span>, (req, res) =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> postData = <span class="string">''</span>;</span><br><span class="line">    <span class="comment">// 监听参数传输事件</span></span><br><span class="line">    req.on(<span class="string">'data'</span>, (params) =&gt; postData += params;);</span><br><span class="line">    <span class="comment">// 监听参数传输完毕事件</span></span><br><span class="line">    req.on(<span class="string">'end'</span>, () =&gt; &#123; </span><br><span class="line">        <span class="built_in">console</span>.log(querystring.parse(postData)); </span><br><span class="line">    &#125;); </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>



</li>
</ul>
<h3 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h3><p>路由是指客户端请求地址与服务器端程序代码的对应关系。简单的说，就是请求什么响应什么。</p>
<p><img src="/images/%E8%B7%AF%E7%94%B1.PNG" alt=""></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//引入http模块</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="comment">//引入url模块</span></span><br><span class="line"><span class="keyword">const</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>);</span><br><span class="line"><span class="comment">//创建服务器</span></span><br><span class="line"><span class="keyword">const</span> app = http.createServer();</span><br><span class="line">app.on(<span class="string">'request'</span>,(req,res)=&gt;&#123;</span><br><span class="line">    <span class="comment">//获取请求方式</span></span><br><span class="line">    <span class="keyword">const</span> method = req.method.toLowerCase();</span><br><span class="line">    <span class="comment">//获取请求路径</span></span><br><span class="line">    <span class="keyword">const</span> pathname = url.parse(req.url).pathname;</span><br><span class="line">    res.writeHead(<span class="number">200</span>,&#123;</span><br><span class="line">        <span class="string">'content-type'</span>:<span class="string">'text/html;charset=utf8'</span></span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">if</span>(method == <span class="string">'get'</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span>(pathname==<span class="string">'/index'</span>||pathname==<span class="string">'/'</span>)</span><br><span class="line">            res.end(<span class="string">'欢迎来到首页'</span>);</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span>(pathname==<span class="string">'/list'</span>)</span><br><span class="line">            res.end(<span class="string">'欢迎来到列表页'</span>);</span><br><span class="line">        <span class="keyword">else</span> </span><br><span class="line">            res.end(<span class="string">'你查找的页面不存在'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br></pre></td></tr></table></figure>



<h1 id="Node-js异步编程"><a href="#Node-js异步编程" class="headerlink" title="Node.js异步编程"></a>Node.js异步编程</h1><p><strong>同步API</strong></p>
<p>只有当前面API执行完毕后才会执行下面代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'before'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'after'</span>);</span><br></pre></td></tr></table></figure>



<p><strong>异步API</strong></p>
<p>当前API的执行不回阻塞后面代码的执行</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'before'</span>);</span><br><span class="line">setTimeout(</span><br><span class="line">	()=&gt;&#123;<span class="built_in">console</span>.log(<span class="string">'last'</span>)</span><br><span class="line">	&#125;,<span class="number">2000</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'after'</span>);</span><br></pre></td></tr></table></figure>

<p>二者区别：<strong>获取返回值</strong></p>
<p><strong>同步API可以从返回值中拿到API执行的结果, 但是异步API是不可以的</strong></p>
<p>同步API</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">  <span class="comment">// 同步</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span> (<span class="params">n1, n2</span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> n1 + n2;</span><br><span class="line">&#125; </span><br><span class="line"><span class="keyword">const</span> result = sum (<span class="number">10</span>, <span class="number">20</span>);   <span class="comment">//result = 30</span></span><br></pre></td></tr></table></figure>

<p>异步API</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getMsg</span> (<span class="params"></span>) </span>&#123; </span><br><span class="line">    setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; </span><br><span class="line">        <span class="keyword">return</span> &#123; <span class="attr">msg</span>: <span class="string">'Hello Node.js'</span> &#125;</span><br><span class="line">    &#125;, <span class="number">2000</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> msg = getMsg (); <span class="comment">//获取不到结果，但不报错</span></span><br></pre></td></tr></table></figure>



<h3 id="回调函数callback"><a href="#回调函数callback" class="headerlink" title="回调函数callback"></a>回调函数callback</h3><p>自己定义函数让别人去调用。（自己做的饭让别人去吃。。）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// getData函数定义</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getData</span> (<span class="params">callback</span>) </span>&#123;&#125;</span><br><span class="line"> <span class="comment">// getData函数调用</span></span><br><span class="line">getData (<span class="function"><span class="params">()</span> =&gt;</span> &#123;&#125;);</span><br></pre></td></tr></table></figure>



<h3 id="使用回调函数获取异步API-的执行结果"><a href="#使用回调函数获取异步API-的执行结果" class="headerlink" title="使用回调函数获取异步API 的执行结果"></a>使用回调函数获取异步API 的执行结果</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getMsg</span> (<span class="params">callback</span>) </span>&#123;</span><br><span class="line">    setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        callback (&#123; <span class="attr">msg</span>: <span class="string">'Hello Node.js'</span> &#125;)</span><br><span class="line">    &#125;, <span class="number">2000</span>);</span><br><span class="line">&#125;</span><br><span class="line">getMsg (<span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123; </span><br><span class="line">    <span class="built_in">console</span>.log(msg);</span><br><span class="line">&#125;); <span class="comment">//得到结果&#123; msg: 'Hello Node.js' &#125;</span></span><br></pre></td></tr></table></figure>



<p>异步API的执行顺序与同步API不同</p>
<p><strong>如果异步API后面代码的执行依赖当前异步API的执行结果，但实际上后续代码在执行的时候异步API还没有返回结果，这个问题要怎么解决呢？</strong></p>
<h1 id="Promise对象"><a href="#Promise对象" class="headerlink" title="Promise对象"></a>Promise对象</h1><p>Promise出现的目的是解决Node.js异步编程中回调地狱的问题。回调地狱：函数作为参数，代码全部一层一层的嵌套,看起来就很庞大,很恶心</p>
<p>使用promise对象解决：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> promiseObj = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">            resolve(&#123;<span class="attr">name</span>: <span class="string">'张三'</span>&#125;)</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            reject(<span class="string">'失败了'</span>) </span><br><span class="line">        &#125; </span><br><span class="line">    &#125;, <span class="number">2000</span>);</span><br><span class="line">&#125;);</span><br><span class="line">promiseObj.then(<span class="function"><span class="params">result</span> =&gt;</span> <span class="built_in">console</span>.log(result)) <span class="comment">// &#123;name: '张三'&#125;)</span></span><br><span class="line">       .catch(<span class="function"><span class="params">error</span> =&gt;</span> <span class="built_in">console</span>.log(error))  <span class="comment">//失败了</span></span><br><span class="line"><span class="comment">//输出&#123; name: '张三' &#125;</span></span><br></pre></td></tr></table></figure>



<h3 id="异步函数"><a href="#异步函数" class="headerlink" title="异步函数"></a>异步函数</h3><p><strong>异步函数是异步编程语法的终极解决方案</strong>，它可以让我们将异步代码写成同步的形式，让代码不再有回调函数嵌套，使代码变得清晰明了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fn = <span class="keyword">async</span> () =&gt; &#123;&#125;  <span class="comment">//函数名前面加上async</span></span><br></pre></td></tr></table></figure>

<ol>
<li><p>普通函数定义前加<code>async</code>关键字 普通函数变成异步函数</p>
</li>
<li><p>异步函数默认返回<code>promise</code>对象</p>
</li>
<li><p>在异步函数内部使用return关键字进行结果返回，结果会被包裹的promise对象中，<code>return</code>关键字代替了resolve方法</p>
</li>
<li><p>在异步函数内部使用<code>throw</code>关键字抛出程序异常</p>
</li>
<li><p>调用异步函数再链式调用<code>then</code>方法获取异步函数执行结果</p>
</li>
<li><p>调用异步函数再链式调用<code>catch</code>方法获取异步函数执行的错误信息</p>
</li>
</ol>
<h4 id="await关键字"><a href="#await关键字" class="headerlink" title="await关键字"></a>await关键字</h4><ol>
<li><p>await关键字只能出现在异步函数中</p>
</li>
<li><p><code>await promise</code> await后面只能写promise对象 写其他类型的API是不可以的</p>
</li>
<li><p>await关键字可是暂停异步函数向下执行 直到promise返回结果</p>
</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">p1</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="string">'p1'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">p2</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="string">'p2'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">p3</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="string">'p3'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">run</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="keyword">let</span> r1 = <span class="keyword">await</span> p1()</span><br><span class="line">	<span class="keyword">let</span> r2 = <span class="keyword">await</span> p2()</span><br><span class="line">	<span class="keyword">let</span> r3 = <span class="keyword">await</span> p3()</span><br><span class="line">	<span class="built_in">console</span>.log(r1)</span><br><span class="line">	<span class="built_in">console</span>.log(r2)</span><br><span class="line">	<span class="built_in">console</span>.log(r3)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">run();</span><br></pre></td></tr></table></figure>

<p>怎么样，相对于回调地狱，是不是整洁了无数倍呢？</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E7%AC%94%E8%AE%B0/" rel="tag"># 服务端笔记</a>
          
            <a href="/tags/Node/" rel="tag"># Node</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/05/18/Node%E5%9F%BA%E7%A1%80/" rel="next" title="Node.js 基础">
                <i class="fa fa-chevron-left"></i> Node.js 基础
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/agul1.png"
                alt="agul" />
            
              <p class="site-author-name" itemprop="name">agul</p>
              <p class="site-description motion-element" itemprop="description">天行健，君子以自强不息</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Node-js-创建Web服务器"><span class="nav-number">1.</span> <span class="nav-text">Node.js 创建Web服务器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#http"><span class="nav-number">2.</span> <span class="nav-text">http</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#请求报文："><span class="nav-number">2.0.1.</span> <span class="nav-text">请求报文：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#响应报文"><span class="nav-number">2.0.2.</span> <span class="nav-text">响应报文</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#GET请求参数"><span class="nav-number">2.0.3.</span> <span class="nav-text">GET请求参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#POST请求参数"><span class="nav-number">2.0.4.</span> <span class="nav-text">POST请求参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#路由"><span class="nav-number">2.0.5.</span> <span class="nav-text">路由</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Node-js异步编程"><span class="nav-number">3.</span> <span class="nav-text">Node.js异步编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#回调函数callback"><span class="nav-number">3.0.1.</span> <span class="nav-text">回调函数callback</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用回调函数获取异步API-的执行结果"><span class="nav-number">3.0.2.</span> <span class="nav-text">使用回调函数获取异步API 的执行结果</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Promise对象"><span class="nav-number">4.</span> <span class="nav-text">Promise对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#异步函数"><span class="nav-number">4.0.1.</span> <span class="nav-text">异步函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#await关键字"><span class="nav-number">4.0.1.1.</span> <span class="nav-text">await关键字</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">agul</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
